#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 获取当前日期
    time(&timev);
    ti = localtime(&timev);

    connect(ui->comboBox_month, SIGNAL(currentIndexChanged(int)), this, SLOT(update_comboBox()));
    connect(ui->pushButton_click, SIGNAL(clicked(bool)), this, SLOT(on_progressBar()));
}

bool MainWindow::isleap(int year){
    if(((year % 4 == 0) && (year % 100 != 0)) || year % 400 == 0)
        return true;
    else
        return false;
}

void MainWindow::update_comboBox(){
    int month = ui->comboBox_month->currentText().toInt();
    int day;
    if(month == 4 || month == 6 || month == 9 || month == 11){
        day = 30;
    }else if(month == 2){
        if(isleap(ui->comboBox_year->currentText().toInt())) day = 28;
        else day = 29;
    }else{
        day = 31;
    }
    ui->comboBox_day->clear();
    for(int i = 1; i <= day; i++){
        ui->comboBox_day->addItem(QString::asprintf("%d", i));
    }
}

void MainWindow::on_progressBar(){
    int year, month;
    ui->label_cal->setText("计算中");
    for(int i = 0; i <= 100; i+=1){
        ui->progressBar->setValue(i);
        QThread::msleep(20);
    }
    year = ti->tm_year + 1900 - ui->comboBox_year->currentText().toInt() - 1;
    if(ti->tm_mon + 1 > ui->comboBox_month->currentText().toInt()){
        year++;
        month = ti->tm_mon + 1 - ui->comboBox_month->currentText().toInt();
    }else if(ti->tm_mon + 1 == ui->comboBox_month->currentText().toInt()){
        year++;
        month = 0;
    }else{
        month = 12 - ui->comboBox_month->currentText().toInt() + ti->tm_mon + 1;
    }
    ui->label_year->setText(QString::asprintf("%02d", year));
    ui->label_month->setText(QString::asprintf("%02d", month));
    ui->label_cal->setText("已完成");
}

MainWindow::~MainWindow()
{
    delete ui;
}
